package com.sl.au.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.sl.au.entity.Division;
import com.sl.au.entity.EventType;
import com.sl.au.entity.Option;
import com.sl.au.entity.Part;
import com.sl.au.service.EventTypeService;
import com.sl.au.service.OptionService;
import com.sl.au.service.UserService;
import com.sl.utils.ExdeUtil;
import com.sl.utils.MsgHelper;

/**
 * 事件管理
 * 
 * @author yangdi
 *
 */
@RestController
@RequestMapping(value = "/ui/eventType")
public class EventTypeController extends BaseController {

	@Autowired
	EventTypeService eventTypeService;
	
	@Autowired
	OptionService optionService;
	
	@Autowired
	UserService userService;
	
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index(){
		ModelAndView modelAndView = this.createLayoutView("eventType/eventTypeindex");
		List<Option> options = optionService.getRepository().findByGroup("事件层级");
		modelAndView.addObject("options", options);
		return modelAndView;
	}
	
	/**
	 * 显示区域结构
	 * @param request
	 * @return
	 */
	@RequestMapping(value="getAllNodes",method = RequestMethod.GET)
	public Map<String,Object> getAllNodes(HttpServletRequest request)
	{
		Map<String,Object> map = new HashMap<String,Object>();
		//List<BussinessLevel> node=null;
		List<EventType> node = null;
		
		//node=bussinessLevelService.getAllNodes();
		node = eventTypeService.getAllNodes();
		List<Map<String,Object>> nodeMap=new ArrayList<Map<String,Object>>();
		
		nodeMap=eventTypeService.getNodeMap(node);
		
		map.put("code", 1);
		map.put("nodes", nodeMap);
	
		return map;
	}
	
	/**
	 * 获取节点信息
	 * @param request
	 * @return
	 */
	@RequestMapping(value="getNode",method = RequestMethod.GET)
	public Map<String,Object> getNode(HttpServletRequest request){
		Map<String,Object> map = new HashMap<String,Object>();
		String Id=request.getParameter("Id");
		EventType node = eventTypeService.getRepository().findOne(Id);
		map.put("node", node);
		return map;
	}
	
	/**
	 * 初始数据
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "getpage", method = RequestMethod.POST)
	public Map<String,Object> getPage(HttpServletRequest request) {
		Map<String,Object> map = new HashMap<String,Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key=request.getParameter("key");
		List<EventType> modules=null;
		long count = 0;
		
		modules = eventTypeService.getEventTypeByKey(start, length, key, null, null);
		count=eventTypeService.getEventTypeByKeyCount(key);
		
		map.put("data", modules);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	
	/**
	 * 初始数据
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "getchildrenpage", method = RequestMethod.POST)
	public Map<String,Object> getchildrenpage(HttpServletRequest request) {
		Map<String,Object> map = new HashMap<String,Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key=request.getParameter("key");
		String id= request.getParameter("id");
		List<EventType> modules=null;
		long count = 0;
		
		modules = eventTypeService.getChildrenEventTypeByKey(start, length, id, key, null, null);
		count=eventTypeService.getChildrenEventTypeByKeyCount(id, key);
		
		map.put("data", modules);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	
	/**
	 * 保存/修改信息
	 * @param map
	 * @return
	 */
	@RequestMapping(value="/save",method = RequestMethod.POST)
	public MsgHelper saveeventType(@RequestBody Map<String,Object> map){
		MsgHelper msgHelper = null;
		String id = (String) map.get("id");
		String eventTypeName = (String) map.get("eventName");
		String eventTypeIdentify = (String) map.get("eventIdentify");
		String eventTypeLevelId = (String) map.get("eventLevel");
		String sEventWeight = (String) map.get("eventWeight");
		String sProcessLimit = (String) map.get("processLimit");
		String sAcceptLimit = (String) map.get("acceptLimit");
		float eventWeight = ExdeUtil.str2float(sEventWeight);
		float processLimit = ExdeUtil.str2float(sProcessLimit);
		float acceptLimit = ExdeUtil.str2float(sAcceptLimit);
		
		boolean userShow = ExdeUtil.str2boolean(map.get("userShow"));
		boolean partShow = ExdeUtil.str2boolean( map.get("partShow"));
		boolean gridShow = ExdeUtil.str2boolean( map.get("gridShow"));
		boolean eventShow = ExdeUtil.str2boolean( map.get("eventShow"));
		
		Option eventTypeLevel = optionService.getRepository().findOne(eventTypeLevelId);
		EventType sameEventType = null;
		EventType eventType = null;
		if(!id.equals("")){
			eventType = eventTypeService.getRepository().findOne(id);
			sameEventType = eventTypeService.getRepository().findTopByEventParentAndEventIdentify(eventType.getEventParent(), eventTypeIdentify);
			if(eventType.getEventParent() == null || sameEventType == null || sameEventType.getId().equals(id)) {
				eventType.setUpdateTime(new Date());
				eventType.setEventWeight(eventWeight);
				eventType.setProcessLimit(processLimit);
				eventType.setAcceptLimit(acceptLimit);
				eventType.setEventName(eventTypeName);
				eventType.setEventIdentify(eventTypeIdentify);
				eventType.setEventLevel(eventTypeLevel);
				
				eventType.setUserShow(userShow);
				eventType.setPartShow(partShow);
				eventType.setGridShow(gridShow);
				eventType.setEventShow(eventShow);
				
				eventTypeService.getRepository().save(eventType);
				msgHelper = MsgHelper.success();
			}else {
				msgHelper = MsgHelper.failed();
				msgHelper.setMsg("此层级存在相同事件编码,不能进行修改!");
			}
		}else{
			eventType = new EventType();
			eventType.setEventWeight(eventWeight);
			eventType.setProcessLimit(processLimit);
			eventType.setAcceptLimit(acceptLimit);
			eventType.setEventName(eventTypeName);
			eventType.setEventIdentify(eventTypeIdentify);
			eventType.setEventLevel(eventTypeLevel);
			
			eventType.setUserShow(userShow);
			eventType.setPartShow(partShow);
			eventType.setGridShow(gridShow);
			eventType.setEventShow(eventShow);
			
			eventTypeService.getRepository().save(eventType);
			msgHelper = MsgHelper.success();
		}
		return msgHelper;
	};
	
	/**
	 * 保存事件层级及上传图标
	 * @param eventType
	 * @param file
	 * @return
	 */
	@RequestMapping(value = "saveEventTypeWithFile", method = RequestMethod.POST)
	public MsgHelper saveDetailWithFile(EventType eventType,@RequestParam(value = "file", required = false) MultipartFile file) {
		MsgHelper msgHelper = null;
		
		if (file.getOriginalFilename() != null && !"".equals(file.getOriginalFilename())) {
			// 注意路径的构建
			String url = getUploadIconFilePath(this.fileUploadPath, "icon/EventType", file);
			eventType.setIconAddress(url);
		}
		
		String eventParent = eventType.getEventParent();
		if(!StringUtils.hasText(eventParent)) {
			eventParent = null;
		}
		
		EventType sameEventType = null;
		if(!eventType.getId().equals("")){
			EventType oldEventType = eventTypeService.getRepository().findOne(eventType.getId());
			sameEventType = eventTypeService.getRepository().findTopByEventParentAndEventIdentify(eventType.getEventParent(), eventType.getEventIdentify());
			if(oldEventType.getEventParent() == null || sameEventType == null || sameEventType.getId().equals(eventType.getId())) {
				oldEventType.setUpdateTime(new Date());
				oldEventType.setEventWeight(eventType.getEventWeight());
				oldEventType.setProcessLimit(eventType.getProcessLimit());
				oldEventType.setAcceptLimit(eventType.getAcceptLimit());
				oldEventType.setEventName(eventType.getEventName());
				oldEventType.setEventIdentify(eventType.getEventIdentify());
				oldEventType.setEventLevel(eventType.getEventLevel());
				
				oldEventType.setFirstRewardScore(eventType.getFirstRewardScore());
				oldEventType.setRewardScore(eventType.getRewardScore());
				oldEventType.setMemo(eventType.getMemo());
				
				oldEventType.setUserShow(eventType.isUserShow());
				oldEventType.setPartShow(eventType.isPartShow());
				oldEventType.setGridShow(eventType.isGridShow());
				oldEventType.setEventShow(eventType.isEventShow());
				
				oldEventType.setIconAddress(eventType.getIconAddress());
				
				oldEventType.setIsMobileShow(eventType.getIsMobileShow());
				
				eventTypeService.getRepository().save(oldEventType);
				msgHelper = MsgHelper.success();
				msgHelper.setMsg("事件层级保存成功!");
			}else {
				msgHelper = MsgHelper.failed();
				msgHelper.setMsg("此层级存在相同事件编码,不能进行修改!");
			}
		}else{
			if(eventParent != null) {
				sameEventType = eventTypeService.getRepository().findTopByEventParentAndEventIdentify(eventType.getEventParent(), eventType.getEventIdentify());
				if(sameEventType == null) {
					EventType newEventType = new EventType();
					newEventType.setEventWeight(eventType.getEventWeight());
					newEventType.setProcessLimit(eventType.getProcessLimit());
					newEventType.setAcceptLimit(eventType.getAcceptLimit());
					newEventType.setEventName(eventType.getEventName());
					newEventType.setEventIdentify(eventType.getEventIdentify());
					newEventType.setEventLevel(eventType.getEventLevel());
					
					newEventType.setFirstRewardScore(eventType.getFirstRewardScore());
					newEventType.setRewardScore(eventType.getRewardScore());
					newEventType.setMemo(eventType.getMemo());
					
					newEventType.setUserShow(eventType.isUserShow());
					newEventType.setPartShow(eventType.isPartShow());
					newEventType.setGridShow(eventType.isGridShow());
					newEventType.setEventShow(eventType.isEventShow());
					
					newEventType.setIconAddress(eventType.getIconAddress());
					
					newEventType.setIsMobileShow(eventType.getIsMobileShow());
					
					int eventTypeOrder = eventTypeService.getRepository().getEventOrder(eventParent);
					newEventType.setEventOrder(eventTypeOrder);
					newEventType.setEventParent(eventParent);
					eventTypeService.getRepository().save(newEventType);
					
					msgHelper = MsgHelper.success();
					msgHelper.setMsg("事件层级新增成功!");
				}else {
					msgHelper = MsgHelper.failed();
					msgHelper.setMsg("此层级存在相同区域编码,不能进行新增!");
				}
				
			}else {
				EventType newEventType = new EventType();
				newEventType.setEventWeight(eventType.getEventWeight());
				newEventType.setProcessLimit(eventType.getProcessLimit());
				newEventType.setAcceptLimit(eventType.getAcceptLimit());
				newEventType.setEventName(eventType.getEventName());
				newEventType.setEventIdentify(eventType.getEventIdentify());
				newEventType.setEventLevel(eventType.getEventLevel());
				
				newEventType.setFirstRewardScore(eventType.getFirstRewardScore());
				newEventType.setRewardScore(eventType.getRewardScore());
				newEventType.setMemo(eventType.getMemo());
				
				newEventType.setUserShow(eventType.isUserShow());
				newEventType.setPartShow(eventType.isPartShow());
				newEventType.setGridShow(eventType.isGridShow());
				newEventType.setEventShow(eventType.isEventShow());
				
				newEventType.setIconAddress(eventType.getIconAddress());
				
				newEventType.setIsMobileShow(eventType.getIsMobileShow());
				
				eventTypeService.getRepository().save(newEventType);
				msgHelper = MsgHelper.success();
				msgHelper.setMsg("事件层级新增成功!");
			}
		}
		
		
		return msgHelper;
	}
	
	/**
	 * 删除信息
	 * @param id
	 * @return
	 */
	@RequestMapping("/delete/{id}")
	public MsgHelper deleteeventType(@PathVariable("id") String id) {
		MsgHelper msgHelper = MsgHelper.success();
		eventTypeService.getRepository().delete(id);
		return msgHelper;
	}
	
	/**
	 * 绑定层级关系
	 * @param map
	 * @return
	 */
	@RequestMapping(value="/saveNode",method = RequestMethod.POST)
	public Map<String,Object> saveNode(@RequestBody Map<String,Object> map){
		Map<String,Object> msg = new HashMap<String,Object>();
		String id = (String) map.get("id");
		String parentId = String.valueOf(map.get("parentId"));
		EventType eventType = eventTypeService.getRepository().findOne(id);
		EventType sameEventType = eventTypeService.getRepository().findTopByEventParentAndEventIdentify(parentId, eventType.getEventIdentify());
		if(sameEventType == null) {
			int eventTypeOrder = eventTypeService.getRepository().getEventOrder(parentId);
			eventType.setEventOrder(eventTypeOrder);
			eventType.setEventParent(parentId);
			eventTypeService.getRepository().save(eventType);
			msg.put("code", 1);
			msg.put("eventType", eventType);
		}else {
			msg.put("code", -1);
			msg.put("msg", "此层级存在相同事件编码,不能进行绑定!");
		}
		
		return msg;
	};
	
	/**
	 * 移除节点信息
	 * @param map
	 * @return
	 */
	@RequestMapping(value="/deleteNodes")
	public Map deleteNode(@RequestBody Map<String,Object> map)
	{
		String str=String.valueOf(map.get("str"));
		//暂未使用
		//String selectPId= String.valueOf(map.get("selectPId"));
		String ids[]=str.split(",");
		//删除用户信息，暂未处理
		//businesssellerBaseInfoService.deleteBussinessLevel(ids);
		eventTypeService.deleteNodes(ids);
		map.put("code", 1);
		return map;
	}
	
	/**
	 * 移动节点信息
	 * @param map
	 * @return
	 */
	@RequestMapping(value="/move")
	public Map moveNode(@RequestBody Map<String,Object> map)
	{
		String id=String.valueOf(map.get("id"));
		String targetId = String.valueOf(map.get("targetId"));
		String moveType = String.valueOf(map.get("moveType"));
		EventType targetNode = eventTypeService.getRepository().findOne(targetId);
		EventType node = eventTypeService.getRepository().findOne(id);
		EventType sameEventType = null;
		String nodeeventTypeParent = node.getEventParent();
		String eventTypeParent = null;
		int eventTypeOrder = 0;
		if("inner".equals(moveType)) {
			eventTypeParent = targetNode.getId();
			sameEventType = eventTypeService.getRepository().findTopByEventParentAndEventIdentify(eventTypeParent, node.getEventIdentify());
			if(sameEventType == null) {
				node.setEventParent(eventTypeParent);
				node.setEventOrder(eventTypeOrder);
				eventTypeService.getRepository().save(node);
			}
		}else {
			eventTypeParent = targetNode.getEventParent();
			sameEventType = eventTypeService.getRepository().findTopByEventParentAndEventIdentify(eventTypeParent, node.getEventIdentify());
			if(sameEventType == null || sameEventType.getId().equals(node.getId())) {
				eventTypeOrder = targetNode.getEventOrder();
				if("next".equals(moveType)) {
					eventTypeOrder = eventTypeOrder + 1;
				}else {
					eventTypeOrder = eventTypeOrder - 1;
				}
				node.setEventParent(eventTypeParent);
				node.setEventOrder(eventTypeOrder);
				eventTypeService.getRepository().save(node);
			}
		}
		if(sameEventType == null || sameEventType.getId().equals(node.getId())) {
			//拉动之后进行重新排序
			eventTypeService.setEventTypeOrder(eventTypeParent);
			//原始数据进行排序
			eventTypeService.setEventTypeOrder(nodeeventTypeParent);
			map.put("code", 1);
		}else {
			map.put("code", -1);
			map.put("msg", "此层级存在相同事件编码,不能进行绑定!");
		}
		
		return map;
	}
}
